package com.googlecode.perfectable.messageable;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.List;

import com.google.common.collect.ImmutableList;

public class CompositeConnectionListener implements ConnectionListener {
	
	public static final CompositeConnectionListener EMPTY =
			new CompositeConnectionListener(ImmutableList.<ConnectionListener> of());

	private final List<ConnectionListener> components;
	
	private CompositeConnectionListener(List<ConnectionListener> components) {
		this.components = components;
	}
	
	public CompositeConnectionListener join(ConnectionListener connectionListener) {
		checkNotNull(connectionListener);
		List<ConnectionListener> newComponents = ImmutableList.<ConnectionListener> builder()
				.addAll(this.components).add(connectionListener).build();
		return new CompositeConnectionListener(newComponents);
	}
	
	@Override
	public void connectionEstablished(Endpoint endpoint) {
		for(ConnectionListener component : this.components) {
			component.connectionEstablished(endpoint);
		}
	}
	
}
